//
//  SuggestionController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/31.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import YYText
import TZImagePickerController
import MobileCoreServices

class SuggestionController: UIViewController, YYTextViewDelegate, TZImagePickerControllerDelegate {
    
    
    var suggestionLabel: UILabel = {
        let label = UILabel()
        label.text = "问题和建议（200字以内）"
        label.font = wwFont_Regular(16)
        label.textColor = UIColor.mg_lightGray
        return label
    }()
    
    var suggestionTextView: YYTextView = {
        let textView = YYTextView()
        textView.backgroundColor = UIColor.white
        textView.font = wwFont_Regular(16)
//        textView.placeholderText = "请简要描述您的问题和意见"
        return textView
    }()
    
    var countLabel: UILabel = {
        let label = UILabel()
        label.font = wwFont_Regular(15)
        label.textColor = UIColor.mg_lightGray
        label.text = "0/200"
        return label
    }()
    
    var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        return view
    }()
    
    var countImageLabel: UILabel = {
        let label = UILabel()
        label.text = "0/4"
        label.font = wwFont_Regular(14)
        label.textColor = UIColor.mg_lightGray
        return label
    }()
    
    var photoArray = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "意见反馈"
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "提交", style: .done, target: self, action: #selector(doSubmitAction))
    self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 15)], for: .normal)
        self.setupViews()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
//        let defaultStand = UserDefaults.standard
//        defaultStand.set(self.suggestionTextView.text, forKey: "suggestionText")
//        defaultStand.set(self.photoArray, forKey: "suggestionImage")
//        var timeCount = 30
//        let codeTimer = DispatchSource.makeTimerSource(queue : DispatchQueue.global())
//        codeTimer.schedule(deadline: .now(),repeating:.seconds(1))
//        codeTimer.setEventHandler(handler: {
//            timeCount = timeCount - 1
//            // 时间到了取消时间源
//            if timeCount <= 0 {
//                codeTimer.cancel()
//            }
//            // 返回主线程处理一些事件，更新UI等等
//            DispatchQueue.main.async {
//                let defaultStand = UserDefaults.standard
//                defaultStand.removeObject(forKey: "suggestionText")
//                defaultStand.removeObject(forKey: "suggestionImage")
//            }
//        })
//        codeTimer.resume()
        super.viewWillDisappear(animated)
        
    }
    func setupViews() {
        self.view.addSubview(self.suggestionLabel)
        self.suggestionLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(64 + 15)
            make.left.equalTo(self.view).offset(20)
            make.height.equalTo(40)
            make.width.equalTo(200)
        }
        
        self.suggestionTextView.delegate = self
        self.view.addSubview(self.suggestionTextView)
        self.suggestionTextView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.suggestionLabel.snp.bottom).offset(10)
            make.height.equalTo(self.view.bounds.height * 0.35)
        }
        
        self.suggestionTextView.addSubview(self.countLabel)
        self.countLabel.snp.makeConstraints { (make) in
            make.width.equalTo(200)
            make.height.equalTo(30)
            make.left.equalTo(self.suggestionTextView).offset(SCREEN_WIDTH - 80)
            make.top.equalTo(self.suggestionTextView).offset(self.view.bounds.height * 0.35 - 40)
        }
        
        self.view.addSubview(self.bottomView)
        self.bottomView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.suggestionTextView.snp.bottom).offset(15)
            make.height.equalTo(SCREEN_HEIGHT * 0.3)
        }
        
        let bottomTitleLabel = UILabel()
        bottomTitleLabel.font = wwFont_Regular(15)
        bottomTitleLabel.text = "请提供相关问题的截图和照片"
        self.bottomView.addSubview(bottomTitleLabel)
        bottomTitleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.bottomView).offset(15)
            make.top.equalTo(self.bottomView).offset(6)
        }
        
        self.bottomView.addSubview(self.countImageLabel)
        self.countImageLabel.snp.makeConstraints { (make) in
            make.right.equalTo(self.bottomView).offset(-10)
            make.top.equalTo(self.bottomView).offset(10)
        }
        
        let vc = PhototPickDemoController()
        self.addChildViewController(vc)
        self.view.addSubview(vc.view)
        vc.view.snp.makeConstraints { (make) in
            make.top.equalTo(self.countImageLabel.snp.bottom)
            make.left.right.equalTo(self.view)
            make.height.equalTo(100)
        }
        vc.photoPickHandler = {[unowned self](photos) in
            self.photoArray = photos
            self.countImageLabel.text = "\(photos.count)" + "/4"
        }
        
    }
    
    @objc func doSubmitAction() {
        guard let content = self.suggestionTextView.text, content.characters.count > 0 else {
            WWInform("内容是空的")
            return
        }
        
        var imgeModelArr = [ImageUploadModel]()
        
        var phoneNumber: String?
        var username: String?
        var guid: String?
        var orderNo: String?
        
        WWBeginLoadingWithStatus("开始提交")
    
        let group = DispatchGroup()
        
        //上传图片
        group.enter()
        if self.photoArray.count > 0  {
            self.uploadImages(completionHandler: { (imageUplodModels) in
                
                
                if imageUplodModels == nil {
                    
                    
                }
                else {
                    
                    imgeModelArr = imageUplodModels!
                }
                group.leave()
            })
        }
        else {
            group.leave()
        }
        
        //获取民工信息
        group.enter()
        self.getMigrantWorkInfo { (aTuple) in
            if aTuple != nil {
                phoneNumber = aTuple!.0
                username = aTuple!.1
            }
            group.leave()
        }
        
        //获取guid
        group.enter()
        UserModel.getGuid { (response) in
            if response.success {
                guid = response.value
            }
            else {
                WWError("获取guid出错")
            }
            group.leave()
        }
        
        //获取orderNo
        group.enter()
        let orderConfigId = "91C9F534-7C53-45A6-9F60-F16722EE9CF7"
        UserModel.getOrderNo(orderConfigId: orderConfigId) { (response) in
            if response.success {
                orderNo = response.value
            }
            else
            {
                WWError("获取orderNo出错")
            }
            group.leave()
        }
        
        group.notify(queue: DispatchQueue.main) {
            guard guid != nil else{
//                WWError("guid是空的")
                return
            }
            guard username != nil, phoneNumber != nil else{
                return
            }
            guard orderNo != nil else {
                return
            }

            var myArr = [[String: String]]()
            
            for item in imgeModelArr {
                guard item.success! else{
                    return
                }
                var dic = [String: String]()
                dic["Name"] = item.name
                dic["Path"] = item.url
                dic["ID"] = item.aId
                
                myArr.append(dic)
            }
            
            SuggestionModel.submitSuggestion(guid:guid!, username: username!, phoneNumber: Int(phoneNumber!)!, orderNo: orderNo!, content: content, imageLists: myArr) {(response) in
                if response.success {
                    WWSuccess("提交成功")
                    self.navigationController?.popViewController(animated: true)
                }
                else {
                    WWError(response.message)
                }
            }
        }

    }
    
    //上传图片
    func uploadImages(completionHandler:@escaping ([ImageUploadModel]?) -> Void) {
        ImageUploadModel.commitImage(self.photoArray) { (response) in
            if response.success {
                completionHandler(response.value)
            }
            else {
                completionHandler(nil)
//                WWError(response.message)
            }
        }
    }
    
    //获取民工信息
    func getMigrantWorkInfo(completionHandler:@escaping ((String, String)?) -> Void) {
        UserInfoModel.getMigrantWorkInfo { (response) in
            if response.success {
                if let value = response.value {
                    if let phoneNumber = value.cellPoneNumber, let username = value.username {
                        completionHandler((phoneNumber, username))
                        return
                    }
                }
                completionHandler(nil)
            }
            else {
                
                completionHandler(nil)
            }
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    
    func textViewDidChange(_ textView: YYTextView) {
        self.countLabel.text = "\(textView.text.characters.count)/200"
        if textView.text.characters.count >= 200 {
            textView.text = textView.text.substring(to: textView.text.index(textView.text.startIndex, offsetBy: 200))
            
            self.countLabel.text = "200/200"
        }
    }
}
